Pinia 是由 Vue 官方所推出的狀態管理工具,主要目的是當資訊在不同元件中共用時傳來傳去很麻煩,因此可以使用 Pinia 將狀態存到 store 中使用。因為是共用 store,所以當其中一個元件更新了資料時,另一個同樣有使用這資料的元件也會更新資料。
Step1: 安裝 dependency 和掛載到 main.js 上
npm install pinia
掛載到 main.js 上
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')
Step2: 新增 stores
在 src 中新增 stores 資料夾,裡面就會放各種類型的狀態,例如計數的範例 (沒錯,它是 GPT 生的w)
// src/stores/counter.js
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCounterStore = defineStore('counter', () => {
const count = ref(0)
function increment() {
count.value++
}
function reset() {
count.value = 0
}
return { count, increment, reset }
})
Step3: 在元件中使用它
引入需要用到的 store
<script setup>
import { useCounterStore } from '@/stores/counter'
import { storeToRefs } from 'pinia'
const counter = useCounterStore()
const { count } = storeToRefs(counter)
</script>
<template>
<div>
<p>現在數字:{{ count }}</p>
<button @click="counter.increment">增加</button>
<button @click="counter.reset">重置</button>
</div>
</template>
在看 Pinia 的時候想到個小小疑問,到底什麼時候會需要用到勒,所有狀態都放進去嗎? 或是有跨不同元件使用的才放? 但..一開始就能夠知道這資料或狀態會跨不同元件嗎?
我自己想了想得出的結論是跨元件再放入,一開始可以先放在 ref 或 reactive 中,如果遇到跨元件需要使用再抽離出來。